package com.bnlr.lrparking.appui.mine.recentparkrecord;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.appui.sharevalue.recharge.TopUpActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.base.BaseResponse;
import com.bnlr.lrparking.constant.ConstantFlag;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.ObservableScrollView;
import com.bnlr.lrparking.widget.photo.PhotoViewerActivity;
import com.bnlr.lrparking.widget.photo.PhotoViewerBean;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.google.gson.Gson;
import com.yolanda.nohttp.NoHttp;
import com.zzti.fengyongge.imagepicker.model.PhotoModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * description: 停车记录详情
 * RecentParkRecordDetailActivity class
 *
 * @author : Licy
 * @date : 2018/12/26
 */
public class RecentParkRecordDetailActivity extends BaseActivity {

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.rela_nav_back)
    RelativeLayout relaNavBack;

    @BindView(R.id.sv_record_detail)
    ObservableScrollView svRecordDetail;
    @BindView(R.id.carport_name)
    TextView carportName;
    @BindView(R.id.carport_address)
    TextView carportAddress;
    @BindView(R.id.car_number)
    TextView carNumber;
    @BindView(R.id.order_number)
    TextView orderNumber;
    @BindView(R.id.car_entry_time)
    TextView carEntryTime;
    @BindView(R.id.car_exit_time)
    TextView carExitTime;
    @BindView(R.id.car_stay_time)
    TextView carStayTime;
    @BindView(R.id.car_contribution)
    TextView carContribution;
    @BindView(R.id.car_payment_status)
    TextView carPaymentStatus;
    @BindView(R.id.car_receipt_status)
    TextView carReceiptStatus;
    @BindView(R.id.car_order_discount)
    TextView carOrderDiscount;
    @BindView(R.id.car_order_pay_value)
    TextView carOrderPayValue;
    @BindView(R.id.car_order_create_time)
    TextView carOrderCreateTime;
    @BindView(R.id.car_order_pay_time)
    TextView carOrderPayTime;

    @BindView(R.id.receipt_recycle_title)
    TextView receiptRecycleTitle;
    @BindView(R.id.ll_receipt_view)
    LinearLayout llReceiptView;
    @BindView(R.id.receipt_grid_view)
    GridView receiptGridView;

    @BindView(R.id.ll_pay_or_upload)
    LinearLayout llPayOrUpload;
    @BindView(R.id.submit_pay_or_upload)
    Button submitPayOrUpload;
    @BindView(R.id.receipt_tips)
    TextView receiptTips;

    @BindView(R.id.rl_pay_and_upload)
    RelativeLayout rlPayAndUpload;
    @BindView(R.id.btn_submit_pay)
    Button btnSubmitPay;
    @BindView(R.id.btn_submit_upload)
    Button btnSubmitUpload;

    @BindView(R.id.ll_hint)
    LinearLayout noData;
    @BindView(R.id.iv_hint)
    ImageView noDataivhint;
    @BindView(R.id.tv_hint_tips)
    TextView noDatatvHint;


    private Context mContext;
    private RecentParkRecordDetailBean.DataBean dataBean;
    private AlertDialog payDialog;
    private String shouYiValue;
    /**
     * 贡献值
     */
    private String contributionValue;
    private String orderNumFromLast;
    private List<String> imgUrls = new ArrayList<>();
    private ReceiptGridViewAdapter gridViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_latestparkrecorddetail);
        ButterKnife.bind(this);

        mContext = this;

        initView();
        initListener();
        initGridView();

        orderNumFromLast = getIntent().getStringExtra("orderNum");
        if (AppConfig.DEBUG) {
            LogUtils.d("orderNum is ", orderNumFromLast);
        }
        getDataByOrderNum(orderNumFromLast);
        getPersonInfo();
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        getPersonInfo();
        getDataByOrderNum(orderNumFromLast);

    }

    /**
     * 初始化页面
     */
    public void initView() {
        tvNavTitle.setText("停车详情");

        btnSubmitPay.setOnClickListener(this);
        btnSubmitUpload.setOnClickListener(this);
        submitPayOrUpload.setOnClickListener(this);
    }


    /**
     * 初始化 grid view，显示小票
     */
    public void initGridView() {

        gridViewAdapter = new ReceiptGridViewAdapter(mContext, imgUrls);
        receiptGridView.setAdapter(gridViewAdapter);
        receiptGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PhotoViewerBean bean = new PhotoViewerBean(imgUrls, 0);
                Intent intent = new Intent(mContext, PhotoViewerActivity.class);
                intent.putExtra(PhotoViewerActivity.PHOTO_VIEWER_TAG, bean);
                startActivity(intent);
            }
        });

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.btn_submit_pay: {
                showPayDialog(contributionValue, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            // 关闭dialog
                            case R.id.dialog_contribution_close:
                                break;
                            // 贡献值充值
                            case R.id.dialog_contribution_charge:
                                startActivity(new Intent(mContext, TopUpActivity.class).putExtra("shouyi", shouYiValue));
                                break;
                            // 支付
                            case R.id.dialog_contribution_pay:
                                contributionPay();
                                break;
                            default:
                                break;
                        }
                        payDialog.dismiss();
                    }
                });
            }
            break;
            case R.id.btn_submit_upload:
                startActivity(new Intent(mContext, SubmitReceiptActivity.class)
                        .putExtra("orderNum", dataBean.getOrderNum()));
                break;
            case R.id.submit_pay_or_upload: {

                // 跳转立即支付
                if (TextUtils.equals(dataBean.getDealStatus(), "1")) {
                    showPayDialog(contributionValue, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            switch (v.getId()) {
                                // 关闭dialog
                                case R.id.dialog_contribution_close:
                                    break;
                                // 贡献值充值
                                case R.id.dialog_contribution_charge:
                                    startActivity(new Intent(mContext, TopUpActivity.class).putExtra("shouyi", shouYiValue));
                                    break;
                                // 支付
                                case R.id.dialog_contribution_pay:
                                    contributionPay();
                                    break;
                                default:
                                    break;
                            }
                            payDialog.dismiss();
                        }
                    });
                }
                // 跳转上传小票
                else {
                    startActivity(new Intent(mContext, SubmitReceiptActivity.class)
                            .putExtra("orderNum", dataBean.getOrderNum()));
                }
            }
            break;
            default:
                break;
        }


    }

    /**
     * 监听
     */
    public void initListener() {

    }

    /**
     * 刷新页面
     */
    public void refreshView(RecentParkRecordDetailBean.DataBean data) {

        // 停车场名称
        carportName.setText(data.getName());
        // 停车场地址
        carportAddress.setText(data.getAddress());
        // 车牌号
        carNumber.setText(data.getCarId());
        // 订单号
        orderNumber.setText(data.getOrderNum());
        // 入场时间
        carEntryTime.setText(data.getBeginTime());
        // 出场时间
        carExitTime.setText(data.getEndTime());
        // 停车时长
        carStayTime.setText(data.getParkTime() + ":00");
        // 停车费用
        carContribution.setText(data.getShareValue());
        // 交易状态
        switch (data.getDealStatus()) {
            case "0":
                carPaymentStatus.setText("已支付");
                carPaymentStatus.setTextColor(getResources().getColor(R.color.main_color));
                break;
            case "1":
                carPaymentStatus.setText("待支付");
                carPaymentStatus.setTextColor(getResources().getColor(R.color.text_ea5544));
                break;
            case "2":
                carPaymentStatus.setText("退款中");
                carPaymentStatus.setTextColor(getResources().getColor(R.color.text_ea5544));
                break;
            case "3":
                carPaymentStatus.setText("已退款");
                carPaymentStatus.setTextColor(getResources().getColor(R.color.text_333333));
                break;
            default:
                break;
        }
        // 小票状态
        switch (data.getIsUpload()) {
            case "0":
                carReceiptStatus.setText("无");
                carReceiptStatus.setTextColor(Color.parseColor("#333333"));
                break;
            case "1":
                carReceiptStatus.setText("审核中");
                carReceiptStatus.setTextColor(Color.parseColor("#ea5544"));
                break;
            case "2":
                carReceiptStatus.setText("审核失败");
                carReceiptStatus.setTextColor(Color.parseColor("#ea5544"));
                break;
            case "3":
                carReceiptStatus.setText("审核成功");
                carReceiptStatus.setTextColor(Color.parseColor("#00caa3"));
                break;
            default:
                break;
        }
        // 优惠
        carOrderDiscount.setText(data.getDiscountMoney());
        // 实际支付
        carOrderPayValue.setText(data.getPayedMoney());
        // 下单时间
        carOrderCreateTime.setText(data.getCreateTime());
        // 付款时间
        carOrderPayTime.setText(data.getPayedTime());

        // 设置按钮和提示信息显示情况
        setBtnStatus(data.getDealStatus(), data.getIsUpload());

        imgUrls.clear();
        for (int i = 0; i < data.getPhotoList().size(); i++) {
            imgUrls.add(data.getPhotoList().get(i).getPhotoUrl());
        }
        LogUtils.d("imgUrls", imgUrls.toString());

        gridViewAdapter.notifyDataSetChanged();
    }

    /**
     * 设置底部按钮状态
     *
     * @param dealSt    交易状态
     *                  0   已完成
     *                  1   待支付
     *                  2   退款中
     *                  3   已退款
     * @param receiptSt 小票状态
     *                  0   没有小票
     *                  1   审核中
     *                  2   审核失败
     *                  3   有小票
     */
    private void setBtnStatus(String dealSt, String receiptSt) {

        if (AppConfig.DEBUG) {
            LogUtils.d("dealSt is " + dealSt, "receiptSt is" + receiptSt);
        }

        switch (dealSt) {
            case "0": {
                switch (receiptSt) {
                    case "0":
                    case "2":
                        llPayOrUpload.setVisibility(View.VISIBLE);
                        llReceiptView.setVisibility(View.GONE);
                        rlPayAndUpload.setVisibility(View.GONE);
                        receiptTips.setVisibility(View.VISIBLE);
                        submitPayOrUpload.setVisibility(View.VISIBLE);
                        submitPayOrUpload.setText("上传小票");
                        break;
                    case "1":
                    case "3":
                        llPayOrUpload.setVisibility(View.GONE);
                        llReceiptView.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;
                }
            }
            break;
            case "1": {
                switch (receiptSt) {
                    case "0":
                    case "2":
                        llPayOrUpload.setVisibility(View.VISIBLE);
                        llReceiptView.setVisibility(View.GONE);
                        rlPayAndUpload.setVisibility(View.VISIBLE);
                        receiptTips.setVisibility(View.VISIBLE);
                        submitPayOrUpload.setVisibility(View.GONE);
                        break;
                    case "1":
                    case "3":
                        llPayOrUpload.setVisibility(View.GONE);
                        llReceiptView.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;
                }
            }
            break;
            case "2":
                llPayOrUpload.setVisibility(View.GONE);
                llReceiptView.setVisibility(View.VISIBLE);
                break;
            case "3":
                llPayOrUpload.setVisibility(View.GONE);
                llReceiptView.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }

    }

    /**
     * 根据订单号获取详情
     *
     * @param orderNum 停车订单号
     */
    public void getDataByOrderNum(String orderNum) {

        if (orderNum == null) {
            LogUtils.e("orderNum is Null !!!");
            return;
        }

        mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
        mRequest.add("action", "GetOrderDetail");
        mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
        mRequest.add("phonePara", Application.DEVICE_ID);
        mRequest.add("orderNum", orderNum);

        CallServer.getRequestInstance().add(mContext,
                mRequest,
                new CustomHttpListener<RecentParkRecordDetailBean>(mContext, true, RecentParkRecordDetailBean.class) {

                    @Override
                    public void doWork(RecentParkRecordDetailBean data, String code) {

                    }

                    @Override
                    public void onFinally(JSONObject obj, String code, boolean isSucceed) throws JSONException {
                        super.onFinally(obj, code, isSucceed);

                        boolean haveData = TextUtils.equals(code, ConstantFlag.STRING_FLAG_ONE);
                        switchView(haveData);
                        if (haveData) {
                            Gson gson = new Gson();
                            RecentParkRecordDetailBean detailBean = gson.fromJson(obj.toString(), RecentParkRecordDetailBean.class);
                            dataBean = new RecentParkRecordDetailBean.DataBean(detailBean.getData());
                            refreshView(detailBean.getData());
                        }

                    }
                }, false);
    }


    /**
     * 显示支付dialog
     *
     * @param contributionExistValue 当前剩余的贡献值
     * @param listener               监听器
     */
    public void showPayDialog(String contributionExistValue, View.OnClickListener listener) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.MyDialog);
        View contentView = getLayoutInflater().inflate(R.layout.dialog_payforpark, null);

        ImageView ivClose = (ImageView) contentView.findViewById(R.id.dialog_contribution_close);
        TextView tvContributionValue = (TextView) contentView.findViewById(R.id.dialog_contribution_value);
        RelativeLayout rlContributionCharge = (RelativeLayout) contentView.findViewById(R.id.dialog_contribution_charge);
        Button btnContributionPay = (Button) contentView.findViewById(R.id.dialog_contribution_pay);
        TextView tvContributionExist = (TextView) contentView.findViewById(R.id.dialog_contribution_exist);

        ivClose.setOnClickListener(listener);
        tvContributionValue.setText(dataBean.getPayedMoney());
        rlContributionCharge.setOnClickListener(listener);
        btnContributionPay.setOnClickListener(listener);
        tvContributionExist.setText(getString(R.string.contribution_exist, contributionExistValue));

        builder.setCancelable(true);

        payDialog = builder.create();
        payDialog.show();
        payDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        payDialog.getWindow().setGravity(Gravity.BOTTOM);

    }


    /**
     * 获取贡献值  收益值
     */
    private void getPersonInfo() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetUserInfoById");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            // 添加到请求队列
            CallServer.getRequestInstance().add(mContext, mRequest,
                    new CustomHttpListener<JSONObject>(mContext, false, null) {
                        @Override
                        public void doWork(JSONObject data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (ConstantFlag.STRING_FLAG_ONE.equals(code)) {
                                    JSONObject object = obj.getJSONObject("data");
                                    //贡献值
                                    contributionValue = object.getString("sharevalue");
                                    // 收益值
                                    shouYiValue = object.getString("incomevalue");
                                } else {

                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {

        }
    }


    /**
     * 贡献值支付
     */
    public void contributionPay() {

        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "PayedByOrderNum");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("payedMoney", dataBean.getPayedMoney());
            mRequest.add("shareValue", contributionValue);
            mRequest.add("orderNum", dataBean.getOrderNum());

            // 添加到请求队列
            CallServer.getRequestInstance().add(mContext, mRequest,
                    new CustomHttpListener<BaseResponse>(mContext, false, null) {

                        @Override
                        public void doWork(BaseResponse data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            try {
                                if (isSucceed) {

                                    if ((obj.getInt("errorCode") == 0) && code.equals("1")) {
                                        // 网络异常
                                        startActivity(new Intent(mContext, ContributionPayResult.class).putExtra("result", 0));
                                    } else {
                                        // 贡献值不足
                                        startActivity(new Intent(mContext, ContributionPayResult.class).putExtra("result", 1));
                                    }
                                } else {
                                    // 网络异常
                                    startActivity(new Intent(mContext, ContributionPayResult.class).putExtra("result", 2));
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    }, false);
        } catch (Exception e) {

        }

    }


    /**
     * 切换页面
     *
     * @param isHaveData 是否有数据
     */
    public void switchView(boolean isHaveData) {
        LogUtils.i("switchView start + isHaveData " + isHaveData);

        if (isHaveData) {
            svRecordDetail.setVisibility(View.VISIBLE);
            noData.setVisibility(View.GONE);
            noDatatvHint.setVisibility(View.GONE);
            noDataivhint.setVisibility(View.GONE);
        } else {
            svRecordDetail.setVisibility(View.GONE);
            noData.setVisibility(View.VISIBLE);
            noDatatvHint.setVisibility(View.VISIBLE);
            noDatatvHint.setText("暂无数据~~");
            noDataivhint.setVisibility(View.VISIBLE);
            noDataivhint.setImageResource(R.mipmap.norecord);
        }
    }
}

